<?php

namespace App\Admin\Controllers;

use Illuminate\Routing\Controller;
use Encore\Admin\Form;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Layout\Row;
use Encore\Admin\Grid;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;
use App\Models\Cate;
use App\Models\App;

class CateController extends Controller
{

	protected $model;
	protected $app;


    /**
     * Index interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function index(Content $content,App $app)
    {
		$this->app  = $app;
		
		$this->model = $model = cate_model($app->name);

		return $content
				->breadcrumb( 
					['text' => '项目管理', 'url' => 'item'],
					['text' => $app->title.'分类管理']
				)
				->title($app->title.'分类管理')
				->description(trans('admin.list'))
				->row(function (Row $row)  use ($app,$model){
					$row->column(6, $this->treeView()->render());
					$row->column(6, function (Column $column) use ($app,$model){    //create部分
						$form = new \Encore\Admin\Widgets\Form();
						$form->action(route('admin.cate.store',['app'=>$app->name]));
						//不允许生成或修改时改变parent_id,防止次序混乱
						$form->text('title', trans('admin.title'))->rules('required');
						$form->text('name', '标识')->rules('required');
						if(!empty($app['sets']['cate']['group'])){
							$form->tags('groups', '分组');
						}
						if(empty($app['sets']['cate']['dir'])){
							$form->switch('publish', '允许发布')->default(1)->states([
									'on'  => ['value' => 1, 'text' => '是'],
									'off' => ['value' => 0, 'text' => '否'],
								]);
						}
						$form->hidden('app_name')->default($app->name);
						$column->append((new Box(trans('admin.new'), $form))->style('success'));
					});
				});

    }

	public function create(Content $content,App $app){
		return redirect()->route('admin.cate.index', ['app'=>$app->name]);
	}


    /**
     * Store a newly created resource in storage.
     *
     * @return mixed
     */
    public function store(App $app)
    {
		$this->app = $app;
		$this->model = cate_model($app->name);
		//dump($app);
		//dd(request()->all());
		return $this->form()->store();
    }

    /**
     * Redirect to edit page.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function show(App $app,$id)
    {        
		return redirect()->route('admin.cate.edit', ['app'=>$app->name,'id' => $id]);
    }

    /**
     * Edit interface.
     *
     * @param string  $id
     * @param Content $content
     *
     * @return Content
     */
    public function edit(Content $content,App $app,$id)
    {
		$this->app = $app;
		$this->model = cate_model($app->name);
		
		return $content
            ->title('分类')
            ->description(trans('admin.edit'))
			->breadcrumb(['text' => '项目管理', 'url' => 'item'],['text' => '分类管理','url'=>'cate/'.$app->name],['text' => '分类编辑'])
            ->row($this->form()->edit($id));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(App $app,$id)
    {
		$this->app = $app;
		$this->model = cate_model($app->name);
		return $this->form()->update($id);
    }



    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(App $app,$id)
    {
        if(empty($id)){
			$response = [
                'status'  => false,
                'message' => '未指定操作记录d',
            ];
			return response()->json($response);
        }        
		$this->app = $app;
		$this->model = cate_model($app->name);
		return $this->form()->destroy($id);
    }
  


    /**
     * @return \Encore\Admin\Tree
     */
    protected function treeView()
    {
		$app = $this->app;
		$model = $this->model;
		$canset =  empty($app['sets']['cate']['set'])? 'admin.tree.catebranch' : 'admin.tree.catebranchset'; 
		
        return $model->tree(function (Tree $tree) use($canset){
			$tree->setView([
					'tree'   => 'admin::tree',
					'branch' => $canset,
				]);
            $tree->disableCreate();	
            $tree->branch(function ($branch){
                $payload = "&nbsp;<strong>{$branch['title']}</strong> -- {$branch['name']}";
                return $payload;
            });
        });
    }



    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $app=$this->app;
		$form = new Form($this->model);
        $form->display('id', 'ID');
		$form->hidden('app_name')->default($app->name);
		//$form->hidden('parent_id');
        $form->text('title', trans('admin.title'))->rules('required');
		$form->text('name', '标识')
			->creationRules(['required','regex:/^[A-Za-z][A-Za-z0-9_]+$/', "unique:cates,name,0,id,app_name,".$app->name])
			->updateRules(['required','regex:/^[A-Za-z][A-Za-z0-9_]+$/', "unique:cates,name,{{id}},id,app_name,".$app->name]);
		if(!empty($app['sets']['cate']['group'])){
			$form->tags('groups', '分组');
		}
		if(empty($app['sets']['cate']['dir'])){
			$form->switch('publish', '允许发布')->default(1)->states([
					'on'  => ['value' => 1, 'text' => '是'],
					'off' => ['value' => 0, 'text' => '否'],
				]);
		}
        return $form;
    }




    /**
     * Make a set form.
     *
     * @return Form
     */
    public function set(Content $content,App $app)
    {
		dump(get_file_type('files/2019-10-27/aaa.jpeg'));
		dd(get_file_type('files/2019-10-27/aaa.rarss'));
		$id = request('id');
		$app = get_app_cate($app,$id);
		
		$app_sets = $app['sets']??[];
		
		$tabs['base'] = '\\App\\Admin\\Forms\\Catesets\\Base';

		if(!empty($app['cate_set_form'])){
			$tabs['app'] = $app['cate_set_form'];  //自定义应用设置
		}
		
		foreach($app_sets['tabs'] as $k=>$v){
			if($v && !empty(config('exts.'.$k.'.cate_set_form')) ){
				$tabs[$k] = config('exts.'.$k.'.cate_set_form');
			}
		}
		
		return $content
            ->title(__('分类应用设置'))
			->breadcrumb(['text' => '项目管理','url'=>'item'],['text' => '分类管理','url'=>'cate/'.$app['name']],['text' => '分类应用设置'])
            ->body(Tab::forms($tabs));

    }
}
